package com.quanquan.store.service;

import DTO.PageDTO;
import com.quanquan.store.dto.AdminDTO;
import com.quanquan.store.entity.Admin;
import com.quanquan.store.entity.Store;
import com.quanquan.store.repository.AdminRepository;
import com.quanquan.store.repository.StoreRepository;
import com.quanquan.store.request.AdminRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import utils.DateUtils;
import utils.DecriptUtils;
import utils.StringUtil;
import utils.UUIDGenerator;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName:AdminService
 * @Description:TODO
 * @Author:xiongjunbao
 * @Date:2019/4/15 13:18
 * @Version 1.0
 */
@Service
public class AdminService {

    private final StoreRepository storeRepository;
    private final AdminRepository adminRepository;
    private final StoreService storeService;

    @Autowired
    public AdminService(AdminRepository adminRepository, StoreRepository storeRepository, StoreService storeService) {
        this.adminRepository = adminRepository;
        this.storeRepository = storeRepository;
        this.storeService = storeService;
    }

    /**
     * 创建核销账户
     *
     * @param request
     * @return
     */
    public boolean addAdmin(AdminRequest request) {
        Admin localAdmin = adminRepository.findByAccount(request.getAccount());
        if (localAdmin != null) {
            return false;
        }
        Admin admin = new Admin();
        admin.setId(UUIDGenerator.getUUID());
        admin.setAccount(request.getAccount());
        String password = DecriptUtils.MD5(request.getPassword());
        admin.setPassword(password);
        admin.setName(request.getName());
        admin.setCreateTime(DateUtils.dateToString(new Date(), DateUtils.TIMESTAMP));
        admin.setUpdateTime(DateUtils.dateToString(new Date(), DateUtils.TIMESTAMP));
        admin.setLevel(request.getLevel());
        admin.setStoreId(request.getStoreId());
        admin.setStatus(0);
        Admin admin1 = adminRepository.saveAndFlush(admin);
        return true;
    }

    /**
     * 强制修改核销账户密码
     *
     * @param request
     * @return
     */
    public boolean updatePassword(AdminRequest request) {
        Admin localAdmin = adminRepository.findByAccount(request.getAccount());
        if (localAdmin == null) {
            return false;
        }
        String password = DecriptUtils.MD5(request.getPassword());
        localAdmin.setPassword(password);
        localAdmin.setUpdateTime(DateUtils.dateToString(new Date(), DateUtils.TIMESTAMP));
        localAdmin.setStoreId(request.getStoreId());
        localAdmin.setStatus(0);
        adminRepository.saveAndFlush(localAdmin);
        return true;
    }


    /**
     * 强制修改核销账户密码
     *
     * @param request
     * @return
     */
    public boolean update(AdminRequest request) {
        Admin localAdmin = adminRepository.findByAdminId(request.getId());
        if (localAdmin == null) {
            return false;
        }
        localAdmin.setName(request.getName());
        String password = DecriptUtils.MD5(request.getPassword());
        localAdmin.setPassword(password);
        localAdmin.setUpdateTime(DateUtils.dateToString(new Date(), DateUtils.TIMESTAMP));
        localAdmin.setStoreId(request.getStoreId());
        localAdmin.setLevel(request.getLevel());
        localAdmin.setStatus(0);
        adminRepository.saveAndFlush(localAdmin);
        return true;
    }

    /**
     * 强制修改核销账户密码
     *
     * @param request
     * @return
     */
    public AdminDTO findById(AdminRequest request) {
        AdminDTO adminDTO = new AdminDTO();
        Admin localAdmin = adminRepository.findByAdminId(request.getId());
        BeanUtils.copyProperties(localAdmin, adminDTO);
        return adminDTO;
    }

    public List<Admin> findAdminById(List<String> adminIds) {
        List<Admin> admins = new ArrayList<>();
        for (String adminId : adminIds) {
            Admin admin = adminRepository.findByAdminId(adminId);
            admins.add(admin);
        }
        return admins;
    }


    /**
     * 强制修改核销账户密码
     *
     * @param request
     * @return
     */
    public boolean findByAccount(AdminRequest request) {
        Admin localAdmin = adminRepository.findByAccount(request.getAccount());
        if (localAdmin != null) {
            return true;
        }
        return false;
    }

    /**
     * 查询核销员列表
     *
     * @param request
     * @return
     */
    public List<AdminDTO> queryList(AdminRequest request) {
        List<AdminDTO> adminDTOS = new LinkedList<>();
        Integer page = null == request.getPage() ? 0 : request.getPage();
        Integer size = null == request.getSize() ? 10 : request.getSize();
        List<Admin> admins = adminRepository.findAllAdmin(page * size, size);
        for (Admin admin : admins) {
            AdminDTO dto = new AdminDTO();
            Store store = storeRepository.findByStoreId(admin.getStoreId());
            dto.setId(admin.getId());
            dto.setAccount(admin.getAccount());
            dto.setName(admin.getName());
            dto.setStoreName(store.getStoreName());
            dto.setLevel(admin.getLevel());
            adminDTOS.add(dto);
        }
        return adminDTOS;
    }


    public PageDTO<AdminDTO> queryByCondition(AdminRequest requestBody) {
        //分页
        Integer page = null == requestBody.getPage() ? 0 : requestBody.getPage();
        Integer size = null == requestBody.getSize() ? 10 : requestBody.getSize();
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        //搜索关键词
        String keyword = requestBody.getKeyword();
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<Admin> paged = adminRepository.findAll((Specification<Admin>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            // 创建具体查询条件
            predicates.add(criteriaBuilder.equal(root.get("status").as(Integer.class), 0));
            if (StringUtil.isNotEmpty(keyword)) {
                /*List<StoreDTO> storeDTOList = storeService.findListByStoreName(keyword);
                if (storeDTOList.size() > 0) {
                    StoreDTO storeDTO = storeDTOList.get(0);
                    predicates.add(criteriaBuilder.equal(root.get("storeId").as(String.class), storeDTO.getId()));
                } else {
                    Predicate p1 = criteriaBuilder.like(root.get("name").as(String.class), "%" + keyword + "%");
                    Predicate p2 = criteriaBuilder.or(criteriaBuilder.like(root.get("account").as(String.class), "%" + keyword + "%"), p1);
                    predicates.add(p2);
                }*/
                Predicate p1 = criteriaBuilder.like(root.get("name").as(String.class), "%" + keyword + "%");
                Predicate p2 = criteriaBuilder.or(criteriaBuilder.like(root.get("account").as(String.class), "%" + keyword + "%"), p1);
                predicates.add(p2);

            }
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        }, pageable);
        PageDTO<AdminDTO> dto = new PageDTO<>();
        List<AdminDTO> adminDTOS = new LinkedList<>();
        for (Admin admin : paged.getContent()) {
            AdminDTO adminDTO = new AdminDTO();
            BeanUtils.copyProperties(admin, adminDTO);
            if (admin.getLevel() != null && admin.getLevel() != 1) {
                Store store = storeRepository.findByStoreId1(admin.getStoreId());
                if (store==null){
                    continue;
                }
                adminDTO.setStoreName(store.getStoreName());
            } else {
                adminDTO.setStoreName("商管账号");
            }
            adminDTOS.add(adminDTO);
        }
        dto.setTotal(paged.getTotalElements());
        dto.setList(adminDTOS);
        dto.setPage(page);
        dto.setPageSize(size);
        dto.setKeyword(requestBody.getKeyword());
        dto.setTotalPage(paged.getTotalPages());
        return dto;
    }

    /**
     * 根据关键词查询会员，会员积分等功能使用
     *
     * @param keyword
     * @return
     */
    public List<Admin> findListByKeyword(String keyword) {
        List<Admin> admins = adminRepository.findAll((Specification<Admin>) (root, query, criteriaBuilder) -> {
            Predicate p = criteriaBuilder.like(root.get("name").as(String.class), "%" + keyword + "%");
            return query.where(p).getRestriction();
        });
        return admins;
    }
}
